//
//  FinishCheckDetailController.m
//  ICrEAM
//
//  Created by mac on 16/11/4.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "FinishCheckDetailController.h"
#import "CheckCollectView.h"
#import "CheckEditDetailFirstCell.h"
#import "CheckLookDetailFirstCell.h"
#import "CheckSecondDetailCell.h"
#import "CheckThirdDetailCell.h"

#import "ICMProxyPreviewViewController.h"
#import "ICMProxyActivityModel.h"
#import "ICMProxyBasicInfoModel.h"

#import "ICMRepairMaintenanceModel.h"
#import "ICMMaintenanceAndPartsView.h"

#import "FinishCheckDetailResponse.h"
#import "FinishCheckDetailAction.h"
#import "FinishCheckSubmitAction.h"
#import "SubmitBtn.h"
#import "AlterImageController.h"

#define isWashStr  @"0"
@interface FinishCheckDetailController ()<UITableViewDelegate,UICollectionViewDelegate>{
    BOOL _optionCheck;
    BOOL _isequal;//文本框类容
}
@property (weak, nonatomic) IBOutlet UILabel *ctrTitleLabel;
//mainTable 距离父控件底部的距离
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *mainTableBottomCostraint;
@property (weak, nonatomic) IBOutlet UITableView *mainTable;
//拍照数组
@property(nonatomic,strong)NSMutableArray *pics;
@property (weak, nonatomic) IBOutlet UIView *submitView;
@property (weak, nonatomic) IBOutlet SubmitBtn *submitBtn;

@property(nonatomic,strong)NSMutableArray *detailArr;
//终检详情模型
@property(nonatomic,strong)FinishCheckDetailResponse *detailResponse;
//选择框的数据源
@property(nonatomic,strong)NSMutableArray *selectArray;
//

//根据活动里面项目和零件  和   项目和零件  生成对应关系数据字典
@property (nonatomic, strong) NSMutableDictionary *labourAndPartsExistDic;
@property (nonatomic, strong) NSMutableArray *activityTempModels;//add del用

@end

@implementation FinishCheckDetailController

-(NSMutableArray *)selectArray{
    if (!_selectArray) {
        _selectArray=[NSMutableArray array];
        NSInteger count;
        if ([ICrEAMTool isVW]) {
            count=7;
        }else{
            count=6;
        }
        for (int i=0; i<count; i++) {
            [_selectArray addObject:@NO];
        }
    }
    return _selectArray;
}
-(NSMutableArray *)pics{
    if (!_pics) {
        _pics=[NSMutableArray array];
    }
    return _pics;
}
-(NSMutableArray *)detailArr{
    if (!_detailArr) {
        if ([ICrEAMTool isVW]) {
             _detailArr= [NSMutableArray arrayWithArray:@[@"车辆内外已清洁",@"《维修服务委托书》所有内容已经完成",@"车上物品齐全，车辆设置已恢复进厂状态",@"车辆外观无额外损坏",@"车辆内饰无额外损坏",@"维修表单、车辆钥匙、证件等准备齐全",@"旧件已包装好。"]];
        }else{
             _detailArr=[NSMutableArray arrayWithArray:@[@"车辆内外已清洁",@"《维修服务委托书》所有内容已经完成",@"车上物品齐全，车辆设置已恢复进厂状态",@"车辆外观无额外损坏",@"车辆内饰无额外损坏",@"维修表单、车辆钥匙、证件等准备齐全"]];
        }
       
    }
    return _detailArr;
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(void)backButtonClick{
    [self.view endEditing:YES];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if ( [ICrEAMUser shareICrEAMUser].checkIsEdit) {
            
            [self alertMessage:@"是否放弃终检？" withSuccessBlock:^{
                [ICrEAMUser shareICrEAMUser].checkIsEdit=NO;
                [super backButtonClick];
            }];
            return;
        }else{
            [super backButtonClick];
        }
    });
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    if (self.isEdit) {
        self.mainTableBottomCostraint.constant=50;
        self.submitView.hidden=NO;
        self.submitBtn.enabled=NO;
        
    }else{
        self.mainTableBottomCostraint.constant=0;
        self.submitView.hidden=YES;
    }
    if (![ICrEAMTool isVW]) {
        self.submitBtn.backgroundColor=KSKBgColor;
        self.ctrTitleLabel.textColor=KSKBgColor;
    }
    [self requestCheckDetail];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteImge:) name:@"deleteImgeNotice" object:nil];
    // Do any additional setup after loading the view.
}
-(void)deleteImge:(NSNotification *)noti{
    NSDictionary *dic=noti.userInfo;
    NSIndexPath *indexPath=dic[@"index"];
    NSInteger index=indexPath.row;
    if (!IsArrEmpty(self.pics)) {
        [self.pics removeObjectAtIndex:index];
    }
    [self.mainTable reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1+self.selectArray.count inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}

-(void)requestCheckDetail{
    FinishCheckDetailAction *action=[[FinishCheckDetailAction alloc]init];
    action.ro_num=self.model.proxyNum;
    [self requestDataWithAction:action haveHud:YES showError:NO  success:^(__kindof YTKBaseRequest *request) {
        id  keyValues = [request.responseString mj_JSONObject];
        if (![keyValues isKindOfClass:[NSDictionary class]]) {
            return;
        }

        self.detailResponse=[FinishCheckDetailResponse mj_objectWithKeyValues:request.responseJSONObject];
        [self.selectArray removeAllObjects];
        if ([self.detailResponse.CHECK_NO1 isEqualToString:isWashStr]) {
            [self.detailArr removeObjectAtIndex:0];
        }else{
        [self.selectArray addObject:[NSNumber numberWithBool:self.detailResponse.isSelectFirst]];
        }
        [self.selectArray addObject:[NSNumber numberWithBool:self.detailResponse.isSelectSecond]];
        [self.selectArray addObject:[NSNumber numberWithBool:self.detailResponse.isSelectThird]];
        [self.selectArray addObject:[NSNumber numberWithBool:self.detailResponse.isSelectFour]];
        [self.selectArray addObject:[NSNumber numberWithBool:self.detailResponse.isSelectFive]];
        [self.selectArray addObject:[NSNumber numberWithBool:self.detailResponse.isSelectSix]];
        if ([ICrEAMTool isVW]) {
            [self.selectArray addObject:[NSNumber numberWithBool:self.detailResponse.isSelectSeven]];
        }
        if (!IsArrEmpty(self.detailResponse.checkImages)) {
            [self.pics addObjectsFromArray:self.detailResponse.checkImages];
        }
        //头部跳转
        self.super_VIN = self.detailResponse.VIN;
        self.super_owner_no = self.detailResponse.OWNER_NO;
        
        
        
        [self.mainTable reloadData];
    } failure:^(__kindof YTKBaseRequest *request) {
        
    }];
}

-(void)didClickICMProxy {
    //
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    [parameters setObject:self.model.proxyNum forKey:@"RO_NO"];
    ICMRequestManager *manager = [[ICMRequestManager alloc]init];
    [manager startGetRequestWithURL:RepairOrderDetils parameters:parameters inHudView:self.view andResultBlock:^(id data, NSString *failText) {
        NSMutableArray *activityModels=[NSMutableArray array];
        
        ICMProxyBasicInfoModel *basicModel = [[ICMProxyBasicInfoModel alloc]init];
        if (IsArr(data[@"TT_REPAIR_ORDER"])) {
            basicModel = [ICMProxyBasicInfoModel yy_modelWithDictionary:data[@"TT_REPAIR_ORDER"][0]];
        }
        ICMRepairMaintenancesModel *repairMaintenancesModel = [ICMRepairMaintenancesModel yy_modelWithDictionary:data];
        [repairMaintenancesModel createRepairMaintenanceRoModel];
        ICMRepairPartsArrayModel *repairPartsArrayModel = [ICMRepairPartsArrayModel yy_modelWithDictionary:data];
        [repairPartsArrayModel createRepairPartsRoModel];
        
        NSArray *dataArray = data[@"TT_ACTIVITY"];
        if (dataArray.count != 0 && dataArray) {
            for (NSDictionary *activityData in dataArray) {
                ICMProxyActivityViewModel *model = [[ICMProxyActivityViewModel alloc]init];
                model.title = activityData[@"ACTIVITY_NAME"];
                model.type = activityData[@"ACTIVITY_TYPE"];
                model.subTitle = activityData[@"ACTIVITY_CODE"];
                model.startTime = [ICrEAMTool getDateWithTimeInterval:activityData[@"SALES_DATE_BEGIN"]];
                model.endTime = [ICrEAMTool getDateWithTimeInterval:activityData[@"SALES_DATE_END"]];
                [activityModels addObject:model];
            }
            for (ICMProxyActivityViewModel *viewModel in activityModels) {
                NSString *url = [NSString stringWithFormat:@"/INFO_ICREAM_WEB/App/queryActivityDetail"];
                NSMutableDictionary *dic=[NSMutableDictionary dictionary];
                [dic setObject:viewModel.subTitle forKey:@"ACTIVITY_CODE"];
                [[[ICMRequestManager alloc]init] startGetRequestWithURL:url parameters:dic inHudView:self.view andResultBlock:^(id data, NSString *failText) {
                    if (!failText) {
                        NSArray *labelArray = data[@"TT_ACTIVITY_LABOUR"];
                        NSArray *partsArray = data[@"TT_ACTIVITY_PART"];
                        for (NSDictionary *labourDic in labelArray) {
//                            ICMProxyActivityLabourModel *labelModel = [ICMProxyActivityLabourModel yy_modelWithJSON:labourDic];
//                            [viewModel.allActivityModel.TT_ACTIVITY_LABOUR addObject:labelModel];
                            
                            //update by panxinfeng
                            ICMRepairMaintenanceModel *labourTempModel = [ICMRepairMaintenanceModel yy_modelWithJSON:labourDic];
                            [viewModel.allActivityModel.TT_ACTIVITY_LABOUR addObject:labourTempModel];
                        }
                        for (NSDictionary *partDic in partsArray) {
//                            ICMProxyActivityPartsModel *partsModel = [ICMProxyActivityPartsModel yy_modelWithJSON:partDic];
//                            [viewModel.allActivityModel.TT_ACTIVITY_PART addObject:partsModel];
                            
                            //update by panxinfeng
                            ICMRepairPartsModel *partsTempModel = [ICMRepairPartsModel yy_modelWithJSON:partDic];
                            [viewModel.allActivityModel.TT_ACTIVITY_PART addObject:partsTempModel];
                        }
                        
                    }else{
                        
                    }
                }];
            }
        }
        self.activityTempModels = activityModels;
        [self createLabourAndPartsExistDicWithLabour:repairMaintenancesModel WithPart:repairPartsArrayModel];
        ICMProxyPreviewViewController *PVC = [[ICMProxyPreviewViewController alloc]init];
        PVC.isFinishCheck=YES;
        PVC.activityModels = [self previewActivitysWithDic:self.labourAndPartsExistDic];;
        PVC.repairMaintenancesModel = repairMaintenancesModel;
        PVC.proxyBasicInfoModel = basicModel;
        PVC.repairPartsArrayModel = repairPartsArrayModel;
        
        
        
        [self.navigationController pushViewController:PVC animated:YES];
        
        
    }];
}

//根据活动里面项目和零件  和   项目和零件  生成对应关系数据字典
- (void)createLabourAndPartsExistDicWithLabour:(ICMRepairMaintenancesModel *)repairMaintenancesModel WithPart:(ICMRepairPartsArrayModel *)repairPartsArrayModel
{
    [self.labourAndPartsExistDic removeAllObjects];
    for(int i = 0;i<self.activityTempModels.count;i++)
    {
        ICMProxyActivityViewModel *actModel = self.activityTempModels[i];
        NSString *actCode = actModel.subTitle;
        NSMutableDictionary *actDic = [[NSMutableDictionary alloc] init];
        //该活动下项目的数组
        NSMutableArray *labourArray = actModel.allActivityModel.TT_ACTIVITY_LABOUR;
        //该活动下项目的字典
        NSMutableDictionary *labourDic = [[NSMutableDictionary alloc] init];
        for(int j = 0;j<labourArray.count;j++)
        {
            ICMRepairMaintenanceModel *labourModel = labourArray[j];
            NSString *labourCode = labourModel.LABOUR_CODE;
            [labourDic setObject:@(NO) forKey:labourCode];
        }
        //该活动下零件的数组
        NSMutableArray *partsArray = actModel.allActivityModel.TT_ACTIVITY_PART;
        //该活动下零件的字典
        NSMutableDictionary *partsDic = [[NSMutableDictionary alloc] init];
        for(int j = 0;j<partsArray.count;j++)
        {
            ICMRepairPartsModel *partModel = partsArray[j];
            NSString *partCode = partModel.PART_NO;
            [partsDic setObject:@(NO) forKey:partCode];
        }
        [actDic setObject:labourDic forKey:@"PANLabour"];
        [actDic setObject:partsDic forKey:@"PANParts"];
        [self.labourAndPartsExistDic setObject:actDic forKey:actCode];
        
        //项目数组
        NSMutableArray *proxyLabourArray = repairMaintenancesModel.TT_RO_LABOUR;
        for(int z = 0;z<proxyLabourArray.count;z++)
        {
            ICMRepairMaintenanceModel *model = proxyLabourArray[z];
            if([model.ACTIVITY_NO isEqualToString:actCode])
            {
                NSMutableDictionary *dic1 = [self.labourAndPartsExistDic objectForKey:actCode];
                NSMutableDictionary *dic2 = [dic1 objectForKey:@"PANLabour"];
                if([dic2 objectForKey:model.LABOUR_CODE])
                    [dic2 setObject:@(YES) forKey:model.LABOUR_CODE];
            }
        }
        
        //∫零件数组
        NSMutableArray *proxyPartsArray = repairPartsArrayModel.TT_RO_REPAIR_PART;
        for(int z = 0;z<proxyPartsArray.count;z++)
        {
            ICMRepairPartsModel *model = proxyPartsArray[z];
            if([model.ACTIVITY_NO isEqualToString:actCode])
            {
                NSMutableDictionary *dic1 = [self.labourAndPartsExistDic objectForKey:actCode];
                NSMutableDictionary *dic2 = [dic1 objectForKey:@"PANParts"];
                if([dic2 objectForKey:model.PART_NO])
                    [dic2 setObject:@(YES) forKey:model.PART_NO];
            }
        }
    }
}

//根据labourAndPartsExistDic 返回被选择的活动的被选择的项目和零件 预览用
- (NSMutableArray *)previewActivitysWithDic:(NSMutableDictionary *)dic
{
    NSMutableArray *temp = [[NSMutableArray alloc] init];
    NSMutableArray *previewActivityArray = [[NSMutableArray alloc] initWithArray:self.activityTempModels];
    for(int z=0;z< previewActivityArray.count;z++)
    {
        ICMProxyActivityViewModel *actModel = previewActivityArray[z];
        if([actModel.IS_CHECKED isEqualToString:@"12781001"])
        {
            NSString *actCode = actModel.subTitle;
            NSMutableDictionary *dic1 = [dic objectForKey:actCode];
            NSMutableDictionary *dic2 = [dic1 objectForKey:@"PANLabour"];
            NSMutableDictionary *dic3 = [dic1 objectForKey:@"PANParts"];
            
            //该活动下项目的数组
            NSMutableArray *tempLabourArray = [[NSMutableArray alloc] init];
            NSMutableArray *labourArray = [[NSMutableArray alloc] initWithArray:actModel.allActivityModel.TT_ACTIVITY_LABOUR];
            //该活动下项目的字典
            for(int i=0;i<labourArray.count;i++)
            {
                ICMRepairMaintenanceModel *labourModel = labourArray[i];
                NSString *labourCode = labourModel.LABOUR_CODE;
                if([dic2 objectForKey:labourCode])
                {
                    if(![[dic2 objectForKey:labourCode] boolValue])
                    {
                        [tempLabourArray addObject:labourModel];
                    }
                }
            }
            for(int ii = 0;ii<tempLabourArray.count;ii++)
            {
                [labourArray removeObject:tempLabourArray[ii]];
            }
            
            actModel.allActivityModel.TT_ACTIVITY_LABOUR = [[NSMutableArray alloc] initWithArray:labourArray];
            //该活动下零件的数组
            NSMutableArray *tempPartsArray = [[NSMutableArray alloc] init];
            NSMutableArray *partsArray = [[NSMutableArray alloc] initWithArray:actModel.allActivityModel.TT_ACTIVITY_PART];
            //该活动下零件的字典
            for(int j=0;j<partsArray.count;j++)
            {
                ICMRepairPartsModel *partModel = partsArray[j];
                NSString *partCode = partModel.PART_NO;
                if([dic3 objectForKey:partCode])
                {
                    if(![[dic3 objectForKey:partCode] boolValue])
                    {
                        [tempPartsArray addObject:partModel];
                        //[partsArray removeObject:partModel];
                    }
                }
            }
            for(int jj = 0;jj<tempPartsArray.count;jj++)
            {
                [partsArray removeObject:tempPartsArray[jj]];
            }
            actModel.allActivityModel.TT_ACTIVITY_PART = [[NSMutableArray alloc] initWithArray:partsArray];
        }
        else
        {
            [temp addObject:actModel];
            //[previewActivityArray removeObject:actModel];
        }
    }
    for(int zz = 0;zz<temp.count;zz++)
    {
        [previewActivityArray removeObject:temp[zz]];
    }
    
    return previewActivityArray;
}

- (NSMutableDictionary *)labourAndPartsExistDic
{
    if(!_labourAndPartsExistDic)
    {
        _labourAndPartsExistDic = [[NSMutableDictionary alloc] init];
    }
    return _labourAndPartsExistDic;
}

-(NSMutableArray *)activityTempModels{
    if (!_activityTempModels) {
        _activityTempModels = [NSMutableArray array];
    }
    return _activityTempModels;
}

#pragma UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger count=(2+self.selectArray.count);
    
    return count;
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==0) {
        if (self.isEdit) {
            CheckEditDetailFirstCell *editCell=[CheckEditDetailFirstCell createCheckEditDetailFirstCell];
            @weakify(self);
            editCell.textReturnBlock=^(BOOL isEqul){
#pragma mark 判断出厂距离文本框和默认值是否相等
                @strongify(self)
                _isequal=isEqul;
                [ICrEAMUser shareICrEAMUser].checkIsEdit=!isEqul;
                
                if (_optionCheck) {
                    [ICrEAMUser shareICrEAMUser].checkIsEdit=YES;
                }
                
            };
            [editCell loadPushInDistance:self.detailResponse.inMileage getCarDistance:self.detailResponse.inMileage license:self.detailResponse.license serviceName:self.detailResponse.serviceAdvisor];
            return editCell;
            
        }else{
            CheckLookDetailFirstCell *lookCell=[CheckLookDetailFirstCell createCheckLookDetailFirstCell];
            [lookCell loadPushInDistance:self.detailResponse.inMileage getCarDistance:self.detailResponse.outMileage license:self.detailResponse.license serviceName:self.detailResponse.serviceAdvisor];
            return lookCell;
            
        }
    }
    if (indexPath.row==(1+self.selectArray.count)) {
        CheckThirdDetailCell *imageCell=[CheckThirdDetailCell createCheckThirdDetailCell];
        imageCell.statusLabel.text=self.detailResponse.oldPartBack;
        imageCell.isEdit=self.isEdit;
        @weakify(self);
        imageCell.imageBlock=^(){
            //调用相机
            @strongify(self);
            [self setimagepickerWithSourceType:UIImagePickerControllerSourceTypeCamera];
            //            UIAlertController *alert=[UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            //
            //
            //            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //                [self setimagepickerWithSourceType:UIImagePickerControllerSourceTypeCamera];
            //            }];
            //            UIAlertAction *photoLibrary = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //                [self setimagepickerWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
            //            }];
            //            [alert addAction:okAction];
            //            [alert addAction:photoLibrary];
            //
            //            //        [alert showViewController:self sender:self.view];
            //            alert.modalPresentationStyle=UIModalPresentationPopover;
            //            UIPopoverPresentationController *pop=alert.popoverPresentationController;
            //            pop.permittedArrowDirections=UIPopoverArrowDirectionUnknown;
            //            pop.sourceRect=CGRectMake(0, 0,ScreenWidth, (ScreenHeight-64)/2);
            //            pop.sourceView=self.view;
            //            [self presentViewController:alert animated:YES completion:nil];
        };
        imageCell.imageCollectioView.photoes=self.pics;
        
        return imageCell;
        
    }
    
    CheckSecondDetailCell *scell=[CheckSecondDetailCell createCheckSecondDetailCell];
    NSNumber *bo=self.selectArray[indexPath.row-1];
    scell.isEdit=self.isEdit;
    scell.isSelect=bo.boolValue;
    scell.indexPath=indexPath;
    @weakify(self)
    scell.selectBlock=^(NSInteger index,BOOL isSelected){
#pragma mark 点击单选框事件
        @strongify(self);
        [self.selectArray replaceObjectAtIndex:index withObject:[NSNumber numberWithBool:isSelected]];
        BOOL enAble=YES;
        BOOL checkEdit=NO;
        for (NSNumber *boolNum in self.selectArray) {
            if (!boolNum.boolValue) {
                enAble=NO;
            }
            if (boolNum.boolValue) {
                checkEdit=YES;
            }
        }
        _optionCheck=checkEdit;
        [ICrEAMUser shareICrEAMUser].checkIsEdit=checkEdit;
        if (!_isequal) {
            [ICrEAMUser shareICrEAMUser].checkIsEdit=YES;
        }
        self.submitBtn.enabled=enAble;
    };
    
    if (indexPath.row>1) {
        scell.contentView.backgroundColor=RGB(243, 243, 243);
    }
    if (indexPath.row==([self.detailResponse.CHECK_NO1 isEqualToString:isWashStr]?1:2)) {
        scell.actionBtn.hidden=NO;
        if ([ICrEAMTool isVW]) {
            [scell.actionBtn setBackgroundImage:[UIImage imageNamed:@"lookproxy_image"] forState:UIControlStateNormal];
        }else{
            [scell.actionBtn setBackgroundImage:[UIImage imageNamed:@"lookproxy_image_sk"] forState:UIControlStateNormal];
        }
        @weakify(self);
        scell.showImageViewBlock=^(){
            @strongify(self);
#pragma mark 查看委托书
            [self didClickICMProxy];
        };
    }
    if (indexPath.row==([self.detailResponse.CHECK_NO1 isEqualToString:isWashStr]?2:3)) {
        scell.contenLabel.hidden=NO;
        if (!IsStrEmpty(self.detailResponse.vhclGoods)) {
            scell.contenLabel.text=self.detailResponse.vhclGoods;
        }
        
    }
    if (indexPath.row==([self.detailResponse.CHECK_NO1 isEqualToString:isWashStr]?3:4)) {
        scell.actionBtn.hidden=NO;
        if (IsStrEmpty(self.model.receptionNum)) {
            scell.actionBtn.hidden=YES;
        }
        if ([ICrEAMTool isVW]) {
            [scell.actionBtn setBackgroundImage:[UIImage imageNamed:@"in_image"] forState:UIControlStateNormal];
        }else{
            [scell.actionBtn setBackgroundImage:[UIImage imageNamed:@"in_image_sk"] forState:UIControlStateNormal];
        }
        
        @weakify(self);
        scell.showImageViewBlock=^(){
            
#pragma mark 查看外部坚持图片
            @strongify(self);
            AlterImageController *alterOutCtr=[[AlterImageController alloc]init];
            alterOutCtr.bigUrlStr=self.detailResponse.outerBigImageUrl;
            alterOutCtr.imageS=self.detailResponse.outerSmallImages;
            __weak typeof(alterOutCtr) weakOuter=alterOutCtr;
            [alterOutCtr setDismissBlock:^{
                [weakOuter removeFromParentViewController];
            }];
            [alterOutCtr showOnView:[[UIApplication sharedApplication] keyWindow]];
            [self addChildViewController:alterOutCtr];
        };
    }
    if (indexPath.row==([self.detailResponse.CHECK_NO1 isEqualToString:isWashStr]?4:5)) {
        
        scell.actionBtn.hidden=NO;
        if (IsStrEmpty(self.model.receptionNum)) {
            scell.actionBtn.hidden=YES;
        }
        if ([ICrEAMTool isVW]) {
            [scell.actionBtn setBackgroundImage:[UIImage imageNamed:@"in_image"] forState:UIControlStateNormal];
        }else{
            [scell.actionBtn setBackgroundImage:[UIImage imageNamed:@"in_image_sk"] forState:UIControlStateNormal];
        }
        @weakify(self);
        scell.showImageViewBlock=^(){
            @strongify(self);
            
#pragma mark 查看内部检查图片
            AlterImageController *alterInnerCtr=[[AlterImageController alloc]init];
            alterInnerCtr.isInner=YES;
            alterInnerCtr.bigUrlStr=self.detailResponse.innerBigImageUrl;
            alterInnerCtr.imageS=self.detailResponse.innerSmallImages;;
            __weak typeof(alterInnerCtr) weakInner=alterInnerCtr;
            [alterInnerCtr setDismissBlock:^{
                
                [weakInner removeFromParentViewController];
            }];
            [ alterInnerCtr showOnView:[[UIApplication sharedApplication] keyWindow]];
            [self addChildViewController:alterInnerCtr];
        };
    }
    if ([ICrEAMTool isVW]) {
        if (indexPath.row==self.selectArray.count) {
            scell.truckShowLabel.text=self.detailResponse.oldPartProcess;
        }
    }
    scell.titleL.text=self.detailArr[indexPath.row-1];
    return scell;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==0) {
        return 90;
    }
    if (indexPath.row==(1+self.detailArr.count)) {
        if ([ICrEAMTool isVW]) {
           return 185;
        }
        return 240;
    }
    return 50;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==0) {
        
    }
}

#warning 写最大照片数判断
-(void)setimagepickerWithSourceType:(UIImagePickerControllerSourceType)type{
    
    if (![UIImagePickerController isSourceTypeAvailable:type]) {
        return;
    }
    UIImagePickerController *imagepicker=[[UIImagePickerController alloc]init];
    imagepicker.delegate=self;
    imagepicker.sourceType=type;
    if (type==UIImagePickerControllerSourceTypePhotoLibrary) {
        imagepicker.modalPresentationStyle=UIModalPresentationPopover;
        UIPopoverPresentationController *pop=imagepicker.popoverPresentationController;
        pop.permittedArrowDirections=UIPopoverArrowDirectionUnknown;
        pop.sourceRect=CGRectMake(300, 0, 100, 100);
        pop.sourceView=self.view;
        [self presentViewController:imagepicker animated:YES completion:nil];
        
    } else
        [self presentViewController:imagepicker animated:YES completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image=info[UIImagePickerControllerOriginalImage];
    
    
    [self.pics addObject:image];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.mainTable reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1+self.selectArray.count inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        
    });
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

-(void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
    viewController.navigationItem.title=@"相册";
}
- (IBAction)submit:(id)sender {
    
    [self alertMessage:@"确认通过终检？" withSuccessBlock:^{
        [self submitData];
    }];
}
#pragma mark 提交终检数据
-(void)submitData{
    [self.view endEditing:YES];
    CheckEditDetailFirstCell *cell=[self.mainTable cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    UITextField *outTextField=[cell viewWithTag:1003];
    NSMutableDictionary *parm=[NSMutableDictionary dictionary];
    if (IsStrEmpty(outTextField.text)) {
        [self showText:@"请输入出厂里程"];
        return;
    }
    if ([outTextField.text doubleValue]<[self.detailResponse.inMileage doubleValue]) {
        [self showText:@"出厂里程必须大于进厂里程"];
        return;
    }
    [parm setObject:outTextField.text forKey:@"OUT_MILEAGE"];
 
    if ([self.detailResponse.CHECK_NO1 isEqualToString:isWashStr]) {
        [parm setObject:@"CHECK_NO1" forKey:isWashStr];
     
    }
    for (int i=0; i<self.selectArray.count; i++) {
        NSString *key=[NSString stringWithFormat:@"CHECK_NO%d",(i+([self.detailResponse.CHECK_NO1 isEqualToString:isWashStr]?2:1))];
        NSNumber *boolNum=self.selectArray[i];
        NSString *code=@"12781002";
        if (boolNum.boolValue) {
            code=@"12781001";
        }
        [parm setObject:code forKey:key];
    }
    if ([self.detailResponse.CHECK_NO1 isEqualToString:isWashStr]) {
        [parm setObject:isWashStr forKey:@"CHECK_NO1"];
        
    }
    self.detailResponse.outMileage=outTextField.text;
    [parm setObject:self.model.proxyNum forKey:@"RO_NO"];
    FinishCheckSubmitAction *action=[[FinishCheckSubmitAction alloc]init];
    action.param=parm;
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    NSMutableArray *allpics=[NSMutableArray array];
    for (id obj in self.pics) {
        if ([obj isKindOfClass:[NSString class]]) {
            NSString *strUrl=obj;
            NSString* key = [manager cacheKeyForURL:[NSURL URLWithString:strUrl]];
            SDImageCache* cache = [SDImageCache sharedImageCache];
           UIImage *image = [cache imageFromDiskCacheForKey:key];
            [allpics addObject:image];
        }else{
            [allpics addObject:obj];
        }
    }
  
    action.images=[allpics mutableCopy];
    [self requestDataWithAction:action haveHud:YES showError:NO  success:^(__kindof YTKBaseRequest *request) {
        
       
        self.isEdit=NO;
        self.mainTableBottomCostraint.constant=0;
        self.submitBtn.enabled=NO;
        self.submitView.hidden=YES;
        [self.mainTable reloadData];
        [ICrEAMUser shareICrEAMUser].checkIsEdit=NO;
        [ICrEAMTool savaOperationReceiptUserName:self.detailResponse.deliverName carSeries:self.detailResponse.seriesName licence:self.detailResponse.license status:@"终检完成" returnTime:   [NSString stringWithFormat:@"%@:00",self.detailResponse.deliverDate]];
        ResponseBase *base=[ResponseBase mj_objectWithKeyValues:request.responseJSONObject];
        [self showText:base.MSG];
        if ([self.delegate respondsToSelector:@selector(finishCheckSucess)]) {
            [self.delegate finishCheckSucess];
        }
    } failure:^(__kindof YTKBaseRequest *request) {
        
    }];
    
}
@end
